package com.harmonk.firstscene.ui

import android.app.Application
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.harmonk.firstscene.db.entity.Road
import com.harmonk.firstscene.ui.model.RoadViewModel
import com.harmonk.firstscene.ui.model.RoadViewModelFactory

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RoadScreen(
    onBackClick: () -> Unit,
    viewModel: RoadViewModel = viewModel(
        factory = RoadViewModelFactory(LocalContext.current.applicationContext as Application)
    )
) {
    val roads by viewModel.roads.observeAsState(emptyList())
    var showAddDialog by remember { mutableStateOf(false) }
    var showEditDialog by remember { mutableStateOf(false) }
    var selectedRoad by remember { mutableStateOf<Road?>(null) }

    LaunchedEffect(Unit) {
        viewModel.loadAllRoads()
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("道路管理") },
                navigationIcon = {
                    IconButton(onClick = onBackClick) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                }
            )
        },
        floatingActionButton = {
            FloatingActionButton(onClick = { showAddDialog = true }) {
                Icon(Icons.Default.Add, contentDescription = "添加道路")
            }
        }
    ) { innerPadding ->
        if (roads.isEmpty()) {
            EmptyRoadState()
        } else {
            RoadList(
                roads = roads,
                onEditRoad = { road ->
                    selectedRoad = road
                    showEditDialog = true
                },
                onDeleteRoad = { road ->
                    viewModel.deleteRoad(road)
                },
                modifier = Modifier
                    .fillMaxSize()
                    .padding(innerPadding)
            )
        }

        // 添加道路对话框
        if (showAddDialog) {
            RoadDialog(
                onDismiss = { showAddDialog = false },
                onConfirm = { road ->
                    viewModel.insertRoad(road)
                    showAddDialog = false
                },
                road = Road()
            )
        }

        // 编辑道路对话框
        if (showEditDialog && selectedRoad != null) {
            RoadDialog(
                onDismiss = { 
                    showEditDialog = false
                    selectedRoad = null
                },
                onConfirm = { road ->
                    viewModel.updateRoad(road)
                    showEditDialog = false
                    selectedRoad = null
                },
                road = selectedRoad!!,
                isEditMode = true
            )
        }
    }
}

@Composable
fun EmptyRoadState() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(
            text = "暂无道路信息",
            style = MaterialTheme.typography.bodyLarge
        )
        Text(
            text = "点击右下角按钮添加道路",
            modifier = Modifier.padding(top = 8.dp),
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

@Composable
fun RoadList(
    roads: List<Road>,
    onEditRoad: (Road) -> Unit,
    onDeleteRoad: (Road) -> Unit,
    modifier: Modifier = Modifier
) {
    LazyColumn(
        modifier = modifier
            .fillMaxSize()
            .padding(horizontal = 8.dp)
    ) {
        items(roads) { road ->
            RoadItem(
                road = road,
                onEdit = { onEditRoad(road) },
                onDelete = { onDeleteRoad(road) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 4.dp)
            )
        }
    }
}

@Composable
fun RoadItem(
    road: Road,
    onEdit: () -> Unit,
    onDelete: () -> Unit,
    modifier: Modifier = Modifier
) {
    var showDeleteDialog by remember { mutableStateOf(false) }

    Card(
        modifier = modifier,
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = road.name,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold
                )
                Row {
                    IconButton(onClick = onEdit) {
                        Icon(
                            imageVector = Icons.Default.Edit,
                            contentDescription = "编辑"
                        )
                    }
                    IconButton(onClick = { showDeleteDialog = true }) {
                        Icon(
                            imageVector = Icons.Default.Delete,
                            contentDescription = "删除"
                        )
                    }
                }
            }

            if (road.upDirection.isNotEmpty()) {
                Text(
                    text = "上行方向: ${road.upDirection}",
                    modifier = Modifier.padding(top = 8.dp),
                    style = MaterialTheme.typography.bodyMedium
                )
            }

            if (road.downDirection.isNotEmpty()) {
                Text(
                    text = "下行方向: ${road.downDirection}",
                    modifier = Modifier.padding(top = 4.dp),
                    style = MaterialTheme.typography.bodyMedium
                )
            }
        }
    }

    if (showDeleteDialog) {
        AlertDialog(
            onDismissRequest = { showDeleteDialog = false },
            title = { Text("确认删除") },
            text = { Text("确定要删除道路 \"${road.name}\" 吗？此操作不可撤销。") },
            confirmButton = {
                Button(
                    onClick = {
                        onDelete()
                        showDeleteDialog = false
                    }
                ) {
                    Text("确认")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = { showDeleteDialog = false }
                ) {
                    Text("取消")
                }
            }
        )
    }
}

@Composable
fun RoadDialog(
    onDismiss: () -> Unit,
    onConfirm: (Road) -> Unit,
    road: Road,
    isEditMode: Boolean = false
) {
    var name by remember { mutableStateOf(road.name) }
    var upDirection by remember { mutableStateOf(road.upDirection) }
    var downDirection by remember { mutableStateOf(road.downDirection) }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(if (isEditMode) "编辑道路" else "添加道路") },
        text = {
            Column {
                TextField(
                    value = name,
                    onValueChange = { name = it },
                    label = { Text("道路名称") },
                    singleLine = true,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 8.dp)
                )
                TextField(
                    value = upDirection,
                    onValueChange = { upDirection = it },
                    label = { Text("上行方向") },
                    singleLine = true,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 8.dp)
                )
                TextField(
                    value = downDirection,
                    onValueChange = { downDirection = it },
                    label = { Text("下行方向") },
                    singleLine = true,
                    modifier = Modifier
                        .fillMaxWidth()
                )
            }
        },
        confirmButton = {
            TextButton(
                onClick = {
                    val newRoad = road.copy(
                        name = name,
                        upDirection = upDirection,
                        downDirection = downDirection
                    )
                    onConfirm(newRoad)
                },
                enabled = name.isNotEmpty()
            ) {
                Text("确认")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}